package copyengine.dataLayer.query.local
{

	public final class CELocalQueryExcuteManger
	{
		private static var _instance:CELocalQueryExcuteManger;

		public static function get instance():CELocalQueryExcuteManger
		{
			if (_instance == null)
			{
				_instance = new CELocalQueryExcuteManger();
			}
			return _instance;
		}

		private var localQueryWarpVector:Vector.<CELocalQueryWarp>;

		public function CELocalQueryExcuteManger()
		{
			localQueryWarpVector = new Vector.<CELocalQueryWarp>();
		}

		public function excuteLocalQuery(_callBackFunction:Function, _uniqueKey:String, _databaseQueryArray:Array):void
		{
			var localQueryWarp:CELocalQueryWarp = getLocalQueryWarpByUniqueKey(_uniqueKey);
			if (localQueryWarp == null)
			{
				localQueryWarp = new CELocalQueryWarp(_uniqueKey, _databaseQueryArray, this);
				localQueryWarpVector.push(localQueryWarp);
			}
			localQueryWarp.addCallbackFunction(_callBackFunction);
			//第一次会执行，第二次不再执行
			localQueryWarp.execute();
		}

		public function removeLocalQueryCallBack(_callBackFunction:Function):void
		{
			for each (var localQueryWarp:CELocalQueryWarp in localQueryWarpVector)
			{
				var result:Boolean = localQueryWarp.removeCallBackFunction(_callBackFunction);
				if (result)
				{
					return;
				}
			}
		}

		public function removeLocalQuery(_query:CELocalQueryWarp):void
		{
			for (var i:int = 0; i < localQueryWarpVector.length; i++)
			{
				if (_query == localQueryWarpVector[i])
				{
					localQueryWarpVector.splice(i, 1);
					break;
				}
			}
		}

		private function getLocalQueryWarpByUniqueKey(_uniqueKey:String):CELocalQueryWarp
		{
			for each (var localQueryWarp:CELocalQueryWarp in localQueryWarpVector)
			{
				if (localQueryWarp.getUniqueKey() == _uniqueKey)
				{
					return localQueryWarp;
				}
			}
			return null;
		}



	}
}
